<?php

namespace Cms;

class Tag extends \Model {
    
    use \State;

    static public $table = 'cms_tag';
    protected $_fillable = [
        'sort' => 'int',
        'state' => 'int',
        'title' => 'str',
    ];
    
    const STATE_ON = 1;
    const STATE_OFF = -1;
    
    protected $_states = [
        self::STATE_ON => '显示',
        self::STATE_OFF => '隐藏',
    ];

    public function getByTitle($title) {
        $where = array('title' => $title);
        return Db()->getRow(static::$table)->where($where)->result();
    }

    public function getList() {
        $where = array('state' => 1);
        return Db()->getAll(static::$table)->where($where)->order('sort desc, id desc')->result();
    }
    
    public function getCacheList() {
        $rows = cache('common', 'tag');
        if (!$rows) {
            $rows = $this->getList();
            cache('common', 'tag', $rows);
        }
        return $rows;
    }

    private function _cache() {
        $rows = $this->getList();
        cache('common', 'tag', $rows);
    }

    public function add($data) {
        $result = parent::add($data);
        if (!$result) {
            return false;
        }

        $this->_cache();

        return $result;
    }

    public function update($id, $data) {
        $result = parent::update($id, $data);
        if (!$result) {
            return false;
        }

        $this->_cache();

        return $result;
    }

    public function remove($id) {
        $result = parent::remove($id);
        if (!$result) {
            return false;
        }

        $this->_cache();

        return $result;
    }

}
